#include"StdAfx.h"
#include"ctype.h"

pgMesh::pgMesh()
{
	m_apVerts = NULL;
	m_apIndices = NULL;

	m_vertexCount = 0;
	m_indexCount = 0;

	m_pVertexBuffer = NULL;
	m_pIndexBuffer = NULL;
}

pgMesh::~pgMesh()
{
	PG_SAFE_DELETE_ARRAY(m_apIndices);
	PG_SAFE_DELETE_ARRAY(m_apVerts);
	PG_SAFE_RELEASE(m_pIndexBuffer);
	PG_SAFE_RELEASE(m_pVertexBuffer);
}


void pgMesh::SetVertices(SVertex *pVerts, int vertexCount)
{
	if(pVerts)
	{
		if(!m_apVerts)
		{
			m_apVerts = pVerts;
			m_vertexCount = vertexCount;
		}
	}
}

void pgMesh::SetIndices(WORD *pIndices, int indexCount)
{
	if (pIndices)
	{
		if (!m_apIndices)
		{
			m_apIndices = pIndices;
			m_indexCount = indexCount;
		}
	}
}

void pgMesh::CreateBuffers()
{
	// TODO
	// Created new every time which is watefull
	// Only create if things have changed
	if (!m_apIndices || !m_apVerts)
	{
		if (!m_apIndices)
			PG_LOG_WARNING_EX(TOPIC_PGRENDERER, "Trying to create index buffer without indices available!");

		if (!m_apVerts)
				PG_LOG_WARNING_EX(TOPIC_PGRENDERER, "Trying to create vertex buffer without vertices available!");

		PG_SAFE_DELETE_ARRAY(m_apIndices);
		PG_SAFE_DELETE_ARRAY(m_apVerts);

		pgMesh *pDefaultCube = pgOBJMeshLoader::LoadMesh(".\\Data\\Meshes\\PaleGemEngine\\defaultCube.obj");

		m_apIndices = pDefaultCube->CopyIndices(m_indexCount);
		m_apVerts = pDefaultCube->CopyVertices(m_vertexCount);

		PG_SAFE_DELETE(pDefaultCube);
	}



	// Release old buffers...
	PG_SAFE_RELEASE(m_pIndexBuffer);
	PG_SAFE_RELEASE(m_pVertexBuffer);


	// Vertex buffer

	D3D11_BUFFER_DESC bd;
	ZeroMemory(&bd, sizeof(bd));
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof(SVertex) * m_vertexCount;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData; 
	ZeroMemory( &InitData, sizeof(InitData) );
	InitData.pSysMem = m_apVerts;

	HRESULT hr = g_PG_pRenderer->m_pd3dDevice->CreateBuffer(&bd, &InitData, &m_pVertexBuffer);

	if (FAILED(hr))
	{
		PG_DX_LOG_ERROR(hr, __FILE__, __LINE__);
		PG_ERROR(ER_D3D_INIT_FAILURE);
	}


	// Index buffer
	ZeroMemory(&bd, sizeof(bd));

	bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof(WORD) * m_indexCount;  
    bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
    bd.CPUAccessFlags = 0;
    bd.MiscFlags = 0;
    InitData.pSysMem = m_apIndices;

	hr = g_PG_pRenderer->m_pd3dDevice->CreateBuffer(&bd, &InitData, &m_pIndexBuffer);

	if (FAILED(hr))
	{
		PG_DX_LOG_ERROR(hr, __FILE__, __LINE__);
		PG_ERROR(ER_D3D_INIT_FAILURE);
	}
}